package com.huike.clues.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huike.clues.domain.SysRole;
import com.huike.clues.domain.SysRoleDept;
import com.huike.clues.domain.SysUser;
import com.huike.clues.domain.dto.DeptListDTO;
import com.huike.clues.domain.dto.SysNewDeptDTO;
import com.huike.clues.domain.entity.Children;
import com.huike.clues.domain.entity.SysDept;
import com.huike.clues.domain.entity.Users;
import com.huike.clues.domain.vo.DeptsVO;
import com.huike.clues.domain.vo.DeptsVO2;
import com.huike.clues.domain.vo.RoleDeptTreeSelectVO;
import com.huike.clues.mapper.DeptMapper;
import com.huike.clues.mapper.SysRoleDeptMapper;
import com.huike.clues.mapper.SysRoleMapper;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.clues.service.DeptService;
import com.huike.common.annotation.AutoFill;
import com.huike.common.constant.ScheduleConstants;
import com.huike.common.enums.FillType;
import com.huike.common.utils.bean.BeanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description DeptServiceImpl
 * @Author bin
 * @Date 2023-10-15
 */
@Service
@RequiredArgsConstructor
public class DeptServiceImpl implements DeptService {

    private final DeptMapper deptMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysRoleDeptMapper sysRoleDeptMapper;
    private final SysUserMapper sysUserMapper;


    /**
     * 处理新增部门请求
     * @param sysDept
     */
    @AutoFill
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(SysDept sysDept) {

        System.out.println(sysDept);

        Long parentId = sysDept.getParentId();
        String ancestors = "";
        Integer count = 0;
        do {
            if (count > 2){
                throw new RuntimeException(SysDept.TOO_LARGE_HIERARCHY);
            }
            //QueryWrapper代表就是条件
            QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
            //添加条件
            queryWrapper.eq("dept_id", parentId);
            SysDept sysDept1 = deptMapper.selectOne(queryWrapper);
            Long parentId1 = sysDept1.getParentId();
            ancestors += parentId1;
            if (parentId1 != 0){
                ancestors += ",";
            }
            parentId = parentId1;
            count++;
        } while (parentId != 0);

        sysDept.setAncestors(ancestors);

        deptMapper.insert(sysDept);


    }


    /**
     * 处理更新部门接口
     * @param sysNewDeptDTO
     */
    @AutoFill(FillType.UPDATE)
    @Override
    public void update(SysNewDeptDTO sysNewDeptDTO) {

        Long parentId = sysNewDeptDTO.getParentId();


        SysDept sysDept1 = deptMapper.selectById(sysNewDeptDTO.getDeptId());
        sysDept1.setDelFlag(SysDept.DELETE);
        deptMapper.updateById(sysDept1);


        SysDept sysDept = new SysDept();
        sysDept.setParentId(parentId);
        BeanUtils.copyProperties(sysNewDeptDTO,sysDept);
        deptMapper.insert(sysDept);


    }



    /**
     * 处理获取部门列表接口
     * @return
     */
    @Override
    public List<SysDept> list(DeptListDTO deptListDTO) {


        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("del_flag",ScheduleConstants.MISFIRE_DEFAULT);

        if (deptListDTO.getDeptName() != null) {
            queryWrapper.like("dept_name",deptListDTO.getDeptName());

            if (deptListDTO.getStatus() != null) {
                queryWrapper.like("status", deptListDTO.getStatus());
            }
        }

        queryWrapper.orderByAsc("order_num");

        List<SysDept> sysDeptList = deptMapper.selectList(queryWrapper);

        return sysDeptList;
    }


    /**
     * 处理根据部门编号获取详细信息
     * @return
     */
    @Override
    public SysNewDeptDTO checkByDeptId(Integer deptId) {

        SysNewDeptDTO sysNewDeptDTO = new SysNewDeptDTO();

        // 查询对应的部门信息并封装
        SysDept sysDept = deptMapper.selectById(deptId);
        BeanUtils.copyProperties(sysDept,sysNewDeptDTO);



        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",sysDept.getDeptId());
        List<SysDept> sysDeptList = deptMapper.selectList(queryWrapper);

        for (SysDept dept : sysDeptList) {
            SysNewDeptDTO sysNewDeptDTO2 = new SysNewDeptDTO();


            SysDept sysDept2 = deptMapper.selectById(dept.getDeptId());
            BeanUtils.copyProperties(sysDept2,sysNewDeptDTO2);


            // 查询用户数据
            QueryWrapper<SysUser> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("dept_id",dept.getDeptId());
            List<SysUser> sysUsers2 = sysUserMapper.selectList(userQueryWrapper2);


            // 查询部门角色表
            QueryWrapper<SysRoleDept> sysRoleDeptQueryWrapper = new QueryWrapper<>();
            sysRoleDeptQueryWrapper.eq("dept_id",dept.getDeptId());
            List<SysRoleDept> sysRoleDepts = sysRoleDeptMapper.selectList(sysRoleDeptQueryWrapper);

            // 获取角色id集
            List<Long> roleList = new ArrayList<>();
            for (SysRoleDept sysRoleDept : sysRoleDepts) {
                Long roleId = sysRoleDept.getRoleId();
                roleList.add(roleId);
            }

            // 获取角色集
            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            sysRoleQueryWrapper.in("role_id",roleList);
            List<SysRole> sysRoles = sysRoleMapper.selectList(sysRoleQueryWrapper);


            List<Users> usersList = new ArrayList<>();
            BeanUtils.copyProperties(sysUsers2,usersList);

            for (Users users : usersList) {
                users.setRoleIds(roleList);
                users.setRoles(sysRoles);

            }

            sysNewDeptDTO2.setUsers(usersList);

        }


        sysNewDeptDTO.setChildren(sysDeptList);


        // 查询用户数据并封装
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("dept_id",deptId);
        List<SysUser> sysUsers = sysUserMapper.selectList(userQueryWrapper);

        List<Users> usersList = new ArrayList<>();
        BeanUtils.copyProperties(sysUsers,usersList);

        sysNewDeptDTO.setUsers(usersList);


        return sysNewDeptDTO;
    }


    /**
     * 处理查询部门列表（排除指定部门节点）
     * @param deptId
     * @return
     */
    @Override
    public List<SysDept> excludeByDeptId(Integer deptId) {

        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<>();
        // 排除父级等于传入deptId
        queryWrapper.ne("parent_id", deptId);

        List<SysDept> sysDeptList = deptMapper.selectList(queryWrapper);

        return sysDeptList;

    }

    /**
     * 处理获取对应角色部门列表树
     * @param roleId
     * @return
     */
    @Override
    public RoleDeptTreeSelectVO roleDeptTreeselect(Integer roleId) {

        RoleDeptTreeSelectVO roleDeptTreeSelectVO = new RoleDeptTreeSelectVO();


        // 获取deptId
        QueryWrapper<SysRoleDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        SysRoleDept sysRoleDept = sysRoleDeptMapper.selectOne(queryWrapper);
        Long deptId = sysRoleDept.getDeptId();


        // 获取父级目录有deptId的数据
        QueryWrapper<SysDept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.like("parent_id",deptId);
        List<SysDept> sysDeptList = deptMapper.selectList(deptQueryWrapper);


        // 部门id集
        List<Long> integerList = new ArrayList<>();
        for (SysDept sysDept : sysDeptList) {
            Long deptId1 = sysDept.getDeptId();
            integerList.add(deptId1);
        }

        roleDeptTreeSelectVO.setCheckedKeys(integerList);

        DeptsVO deptsVO = new DeptsVO(); // 第一层



        // 获取deptId等于deptId的数据
        QueryWrapper<SysDept> deptQueryWrapper1 = new QueryWrapper<>();
        deptQueryWrapper1.eq("dept_id",deptId);
        SysDept sysDept = deptMapper.selectOne(deptQueryWrapper1);

        deptsVO.setId(sysDept.getDeptId());
        deptsVO.setLabel(sysDept.getDeptName());



        List<DeptsVO> deptsVOList = new ArrayList<>();
        for (Long aLong : integerList) {


            DeptsVO deptsVO1 = new DeptsVO();

            QueryWrapper<SysDept> deptQueryWrapper2 = new QueryWrapper<>();
            deptQueryWrapper2.eq("dept_id",aLong);
            SysDept sysDept1 = deptMapper.selectOne(deptQueryWrapper2);

            deptsVO1.setId(sysDept1.getDeptId());
            deptsVO1.setLabel(sysDept1.getDeptName());




/*
            //List<DeptsVO> deptsVOList2 = new ArrayList<>();
            QueryWrapper<SysDept> deptQueryWrapper2 = new QueryWrapper<>();
            deptQueryWrapper2.eq("parent_id",aLong);
            List<SysDept> sysDeptList1 = deptMapper.selectList(deptQueryWrapper2);

*/
            QueryWrapper<SysDept> deptQueryWrapper3 = new QueryWrapper<>();
            deptQueryWrapper3.eq("parent_id",aLong);
            List<SysDept> sysDeptList1 = deptMapper.selectList(deptQueryWrapper3);

            List<DeptsVO> deptsVOList1 = new ArrayList<>();
            for (SysDept dept : sysDeptList1) {

                DeptsVO deptsVO2 = new DeptsVO();
                deptsVO.setId(dept.getDeptId());
                deptsVO.setLabel(dept.getDeptName());
                //deptsVOList.add(deptsVO2);

                deptsVOList1.add(deptsVO2);

            }


            deptsVO1.setChildren(deptsVOList1);


            deptsVOList.add(deptsVO1);


        }


        deptsVO.setChildren(deptsVOList);

        List<DeptsVO> deptsVOList1 = new ArrayList<>();
        deptsVOList1.add(deptsVO);

        roleDeptTreeSelectVO.setDepts(deptsVOList1);


        return roleDeptTreeSelectVO;
    }


    /**
     * 删除部门
     * @param deptId
     */
    @Override
    public void deleteByDeptId(Integer deptId) {
        Boolean deleteFlag = false;

        // 查询并判断部门下相关的用户的删除标记
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("dept_id",deptId);
        List<SysUser> sysUsers = sysUserMapper.selectList(userQueryWrapper);
        for (SysUser sysUser : sysUsers) {
            String delFlag = sysUser.getDelFlag();
            if (delFlag.equals(ScheduleConstants.MISFIRE_FIRE_AND_PROCEED)){
                deleteFlag = true;
            }
        }


        // 判断并获取祖级目录有deptId父级目录为deptId的数据的删除标记
        QueryWrapper<SysDept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.like("ancestors",deptId);
        deptQueryWrapper.eq("parent_id",deptId);
        List<SysDept> sysDeptList = deptMapper.selectList(deptQueryWrapper);
        for (SysDept sysDept : sysDeptList) {
            String delFlag = sysDept.getDelFlag();
            if (delFlag.equals(ScheduleConstants.MISFIRE_FIRE_AND_PROCEED)){
                deleteFlag = true;
            }
        }

        // 判断执行删除
        if(deleteFlag){
            deptMapper.deleteById(deptId);
        }else {
            throw new RuntimeException(SysDept.FAIL_TO_DELETE);
        }



    }


    /**
     * 处理获取部门下拉树列表
     * @return
     */
    @Override
    public List<DeptsVO> treeselect() {

        DeptsVO deptsVO = new DeptsVO();   // 第一层 deptsVO

        // 获取没有父级的列表
        QueryWrapper<SysDept> sysDeptQueryWrapper = new QueryWrapper<>();
        sysDeptQueryWrapper.eq("parent_id",ScheduleConstants.MISFIRE_DEFAULT);
        SysDept sysDept = deptMapper.selectOne(sysDeptQueryWrapper);

        deptsVO.setId(sysDept.getDeptId()); // 第一层 deptsVO Id
        deptsVO.setLabel(sysDept.getDeptName());// 第一层 deptsVO Label

        // 获取没有父级的列表的子列表
        List<DeptsVO> deptsVOList = new ArrayList<>();// 第一层  List<DeptsVO>
        QueryWrapper<SysDept> sysDeptQueryWrapper1 = new QueryWrapper<>();
        sysDeptQueryWrapper1.eq("parent_id",sysDept.getDeptId());
        List<SysDept> sysDeptList = deptMapper.selectList(sysDeptQueryWrapper1);

        for (SysDept dept : sysDeptList) {   // 第一层 List<SysDept> 循环得到第二层

            DeptsVO deptsVO2 = new DeptsVO();  // 第二层 deptsVO

            deptsVO2.setId(dept.getDeptId());  // 第二层 deptsVO Id
            deptsVO2.setLabel(dept.getDeptName());// 第二层 deptsVO Label

            List<DeptsVO> deptsVOList2 = new ArrayList<>();// 第二层 deptsVO LabelList<DeptsVO>

            QueryWrapper<SysDept> sysDeptQueryWrapper2 = new QueryWrapper<>();
            sysDeptQueryWrapper2.eq("parent_id",dept.getDeptId());
            List<SysDept> sysDeptList2 = deptMapper.selectList(sysDeptQueryWrapper2);


            for (SysDept dept1 : sysDeptList2) {  // 第二层 List<SysDept> 循环得到第三层

                DeptsVO deptsVO3 = new DeptsVO(); // 第三层 deptsVO

                deptsVO3.setId(dept1.getDeptId());// 第三层 deptsVO Id
                deptsVO3.setLabel(dept1.getDeptName());// 第三层 deptsVO Label

                List<DeptsVO> deptsVOList3 = new ArrayList<>();// 第三层 deptsVO LabelList<DeptsVO>

                QueryWrapper<SysDept> sysDeptQueryWrapper3 = new QueryWrapper<>();
                sysDeptQueryWrapper3.eq("parent_id",dept1.getDeptId());
                List<SysDept> sysDeptList3 = deptMapper.selectList(sysDeptQueryWrapper3);

                for (SysDept dept2 : sysDeptList3) { //第三层 List<SysDept> 循环得到第四层

                    DeptsVO deptsVO4 = new DeptsVO();// 第四层 deptsVO

                    deptsVO4.setId(dept2.getDeptId());// 第四层 deptsVO Id
                    deptsVO4.setLabel(dept2.getDeptName());// 第四层 deptsVO Label

                    deptsVOList3.add(deptsVO4);// 第三层 deptsVOList 添加

                }


                deptsVO3.setChildren(deptsVOList3);// 第三层 deptsVO Children



                deptsVOList2.add(deptsVO3);// 第二层 deptsVOList 添加


            }

            deptsVO2.setChildren(deptsVOList2);// 第二层 deptsVO Children


            deptsVOList.add(deptsVO2);   // 第一层 deptsVOList 添加

        }


        deptsVO.setChildren(deptsVOList); // 第一层 deptsVO Children

        // 封装类型返回
        List<DeptsVO> list = new ArrayList<>();
        list.add(deptsVO);

        return list;
    }




}
